﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CalcCalorie
{
    public partial class FormEditDish : Form
    {
        bool bOk = false;

        // Каталог
        DIR TypeDish;
        
        // Индекс редактируемого блюда. Если -1 - это добавление блюда
        int EditDishInd = -1;

        public Dish ReturnDish;

        public FormEditDish()
        {
            InitializeComponent();
        }

        /// <summary>Добавление блюда</summary>
        /// <param name="Type">Каталог</param>
        /// <returns></returns>
        public bool ShowDialog(DIR TypeDish)
        {
            return ShowDialog(TypeDish, -1);
        }

        /// <summary>Редактирование блюда</summary>
        /// <param name="Type">Каталог</param>
        /// <returns></returns>
        public bool ShowDialog(DIR TypeDish, int indEditDish)
        {
            this.TypeDish = TypeDish;
            this.EditDishInd = indEditDish;

            if (EditDishInd == -1)
            {
                ReturnDish = new Dish("", TypeDish);
                ReturnDish.Mass = 100;
            }
            else
            {
                ReturnDish = ((Dish)TypeDish.Items[indEditDish]).Clone();
            }

            bOk = false;

            txbName.Text = ReturnDish.Name;

            FillField();
            FillListLb();

            OpenCloseGrbComplex(ReturnDish.IsCompl);

            ShowDialog();
            return bOk;
        }

        private void FormEditDish_Shown(object sender, EventArgs e)
        {
            if (EditDishInd == -1)
            {
                txbName.Focus();
            }
            else
            {
                txbCc.Focus();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            // проверяем правильность введеных полей
            String nm = txbName.Text.Trim();
            if (nm == "")
            {
                MessageBox.Show("Имя блюда не может быть пустым");
                return;
            }

            if (EditDishInd == -1)
            {
                if (TypeDish.IndexOfRecord(nm, "dish") != -1)
                {
                    MessageBox.Show("Блюдо с таким именем уже есть в списке");
                    return;
                }
            }
            else
            {
                if (TypeDish.Items[EditDishInd].Name != nm && TypeDish.IndexOfRecord(nm, "dish") != -1)
                {
                    MessageBox.Show("Блюдо с таким именем уже есть в списке");
                    return;
                }
            }

            ReturnDish.Name = nm;
            bOk = true;
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
       
        double CalcCc()
        {
            double b,g,u;
            double c = 0;
            if (double.TryParse(txbB.Text, out b)) c += b * 4;
            if (double.TryParse(txbG.Text, out g)) c += g * 9;
            if (double.TryParse(txbU.Text, out u)) c += u * 4;
            return Math.Round(c,2);
        }

        bool bSetField = false;
        void FillField()
        {
            bSetField = true;
            if (ReturnDish.IsCompl)
            {
                chbxAutoCalcCc.Checked = true;
                txbCc.ReadOnly = true;
                txbCc.BackColor = SystemColors.Control;

                grCc100.Enabled = false;
                txbMass.Text = ReturnDish.GetTotalMass(1).ToString();
                txbDish.Text = ReturnDish.ToString(1);


                txbCc.Text = Math.Round(ReturnDish.Cc100, 1).ToString();
                if (ReturnDish.B100 == -1) txbB.Text = "";
                else txbB.Text = Math.Round(ReturnDish.B100, 1).ToString();

                if (ReturnDish.G100 == -1) txbG.Text = "";
                else txbG.Text = Math.Round(ReturnDish.G100, 1).ToString();

                if (ReturnDish.U100 == -1) txbU.Text = "";
                else txbU.Text = Math.Round(ReturnDish.U100, 1).ToString();
            }
            else
            {
                grCc100.Enabled = true;
                txbMass.Text = "";
                txbDish.Text = "";

                if (chbxAutoCalcCc.Checked)
                {
                    txbCc.ReadOnly = true;
                    txbCc.BackColor = SystemColors.Control;
                    ReturnDish.Cc100 = CalcCc();
                }
                else
                {
                    txbCc.ReadOnly = false;
                    txbCc.BackColor = SystemColors.Window;
                }

                txbCc.Text = ReturnDish.Cc100.ToString();
                if (ReturnDish.B100 == -1) txbB.Text = "";
                else txbB.Text = ReturnDish.B100.ToString();

                if (ReturnDish.G100 == -1) txbG.Text = "";
                else txbG.Text = ReturnDish.G100.ToString();

                if (ReturnDish.U100 == -1) txbU.Text = "";
                else txbU.Text = ReturnDish.U100.ToString();

            }


           

            bSetField = false;
        }

        private void chbxAutoCalcCc_CheckedChanged(object sender, EventArgs e)
        {
            if (!bSetField)
            {
                FillField();
            }
        }

        bool GetValTxb(TextBox txb, double minVal, ref double Val, bool emptyIsVal)
        {
            if (emptyIsVal && txb.Text.Trim() == "") return false;
            
            double n = 0;
            if (!double.TryParse(txb.Text, out n))
            {
                txb.BackColor = Color.LightCoral;
                return false;
            }
            if (n < minVal)
            {
                txb.BackColor = Color.LightCoral;
                return false;
            }

            if (txb.Text[txb.Text.Length - 1] == ',' || txb.Text[0] == ',')
            {
                txb.BackColor = Color.LightCoral;
                return false;
            }

            
            txb.BackColor = txb.ReadOnly ? SystemColors.Control : SystemColors.Window;
            Val = n;
            return true;
        }

        private void txbCc_TextChanged(object sender, EventArgs e)
        {
            if (!bSetField)
            {
                double n = ReturnDish.Cc100;
                if (GetValTxb(txbCc, 1, ref n, false))
                {
                    ReturnDish.Cc100 = n;
                    FillField();
                }
            }
        }

        private void txbB_TextChanged(object sender, EventArgs e)
        {
            if (!bSetField)
            {
                double n = ReturnDish.B100;
                if (GetValTxb(txbB, 0, ref n, true))
                {
                    ReturnDish.B100 = n;
                    FillField();
                }
            }
        }

        private void txbG_TextChanged(object sender, EventArgs e)
        {
            if (!bSetField)
            {
                double n = ReturnDish.G100;
                if (GetValTxb(txbG, 0, ref n, true))
                {
                    ReturnDish.G100 = n;
                    FillField();
                }
            }
        }

        private void txbU_TextChanged(object sender, EventArgs e)
        {
            if (!bSetField)
            {
                double n = ReturnDish.U100;
                if (GetValTxb(txbU, 0, ref n, true))
                {
                    ReturnDish.U100 = n;
                    FillField();
                }
            }
        }

        void FillListLb()
        {
            lbList.Items.Clear();
            for (int i = 0; i < ReturnDish.dl.Count; i++)
            {
                lbList.Items.Add(ReturnDish.dl[i].Name + " >> " + ReturnDish.dl[i].Mass.ToString() + "гр");
            }
        }

        // добавление блюда
        private void btnAddDish_Click(object sender, EventArgs e)
        {
            FormAddDish frmAdd = new FormAddDish();
            if (frmAdd.ShowDialog(true))
            {
                ReturnDish.dl.Add(frmAdd.ReturnDish.Clone(frmAdd.mass));
                FillListLb();
                FillField();
                btnComplex.Enabled = false;
            }
            frmAdd.Dispose();
        }

        private void lbList_DoubleClick(object sender, EventArgs e)
        {
            int ind1 = lbList.SelectedIndex;
            if (ind1 == -1) return;
            mBtnEditDish_Click(null, null);
        }

        private void menuDish_Opening(object sender, CancelEventArgs e)
        {
            int ind = lbList.SelectedIndex;
            if (ind == -1) e.Cancel = true;
        }

        ESpace.FormEditValue frmEd = new ESpace.FormEditValue();

        private void mBtnEditDish_Click(object sender, EventArgs e)
        {
            Dish actDish = ReturnDish.dl[lbList.SelectedIndex];
            if (frmEd.ShowDialog(actDish.Mass, false, 1, int.MaxValue))
            {
                actDish.Mass = (int)frmEd.Value;
                FillListLb();
                FillField();
            }
        }

        private void mBtnDelDish_Click(object sender, EventArgs e)
        {
            int ind1 = lbList.SelectedIndex;
            if (MessageBox.Show("Действительно удалить?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                ReturnDish.dl.RemoveAt(ind1);
                FillListLb();
                FillField();
                if (!ReturnDish.IsCompl) btnComplex.Enabled = true;
            }
        }

        private void btnComplex_Click(object sender, EventArgs e)
        {
            if (grbCompl.Height == 18)
            {
                OpenCloseGrbComplex(true);
            }
            else
            {
                OpenCloseGrbComplex(false);
            }
        }

        void OpenCloseGrbComplex(bool bOpen)
        {
            if (bOpen)
            {
                grbCompl.Height = 242;
                this.Height = 429;
                grbCompl.ForeColor = SystemColors.ControlText;
                btnComplex.Image = Properties.Resources.downarrow;
            }
            else
            {
                grbCompl.Height = 18;
                this.Height = 207;
                grbCompl.ForeColor = SystemColors.GrayText;
                btnComplex.Image = Properties.Resources.rightarrow;
            }

            btnComplex.Enabled = !ReturnDish.IsCompl;
        }

    }
}
